package com.icoolkj.microservices.inventory.service;

import com.icoolkj.microservices.inventory.InventoryResponse;
import com.icoolkj.microservices.inventory.model.Inventory;
import com.icoolkj.microservices.inventory.repository.InventoryRepository;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author icoolkj
 * @version 1.0
 * @description
 * @createDate 2024/11/12 13:46
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class InventoryService {
    private final InventoryRepository inventoryRepository;

    @Transactional(readOnly = true)
    @SneakyThrows
    public List<InventoryResponse> isInStock(List<String> skuCode){
        List<Inventory> inventoryList = inventoryRepository.findBySkuCodeIn(skuCode);

        Map<String, Inventory> inventoryMap = inventoryList.stream()
                .collect(Collectors.toMap(Inventory::getSkuCode, inventory -> inventory));

        return skuCode.stream()
                .map(code -> {
                    Inventory inventory = inventoryMap.get(code);
                    return InventoryResponse.builder()
                            .skuCode(code)
                            .isInStock(inventory != null && inventory.getQuantity() > 0)
                            .build();
                })
                .toList();
    }
}

